package com.siemens.industrial.web.mvc.controller.partner.tenant;

import com.siemens.industrial.model.admin.SystemConfig;
import com.siemens.industrial.model.partner.Device;
import com.siemens.industrial.model.partner.User;
import com.siemens.industrial.utils.*;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import com.siemens.industrial.web.mvc.service.AuthService;
import com.siemens.industrial.web.mvc.service.WriteLogs;
import com.siemens.industrial.web.mvc.service.admin.SystemConfigService;
import com.siemens.industrial.web.mvc.service.admin.TenantService;
import com.siemens.industrial.web.mvc.service.partner.PartnerDeviceService;
import com.siemens.industrial.web.mvc.service.partner.PartnerUserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/9/1.
 */
@Controller
public class PartnerTenantUserController {
    @Resource
    PartnerUserService partnerTenantService;

    @Resource
    TenantService tenantService;

    @Resource
    PartnerDeviceService partnerDeviceService;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    AuthService authService;

    @Resource
    WriteLogs writeLogs;

    @Resource
    SystemConfigService systemConfigService;

    @RequestMapping(value = "/partner/{tenant}/user/info", method = RequestMethod.GET)
    public String getUser(@PathVariable("tenant") String tenantKey, @RequestParam(value = "userId", required = false) String userId, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        if (tenantId == null)
            return "error";
        User loginUser = (User) authService.currentUser();
        modelMap.put("loginUser", loginUser);
        modelMap.put("key", tenantKey);
        modelMap.put("userInfo", partnerTenantService.getUser(tenantKey, tenantId, userId));
        return "partner/user/userDetail";
    }

    @RequestMapping(value = "/partner/{tenant}/user/setPassword", method = RequestMethod.GET)
    public String setPassword(@PathVariable("tenant") String tenantKey, @RequestParam(value = "userId", required = false) String userId, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        if (tenantId == null)
            return "error";
        modelMap.put("key", tenantKey);
        return "partner/user/updatePassword";
    }

    @RequestMapping(value = "/partner/{tenant}/user/set", method = RequestMethod.GET)
    public String setUser(@PathVariable("tenant") String tenantKey, @RequestParam(value = "userId", required = true) String userId, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        if (tenantId == null)
            return "error";
        List<Map<String, Object>> groupNames = partnerTenantService.getUserGroupName(tenantId);
        modelMap.put("groupNames", groupNames);
        modelMap.put("userInfo", partnerTenantService.getUser(tenantKey, tenantId, userId));
        return "partner/user/updateUser";
    }

    @RequestMapping(value = "/partner/{tenant}/user/list", method = RequestMethod.GET)
    public String getUser(@PathVariable("tenant") String tenantKey, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        User loginUser = (User) authService.currentUser();
        modelMap.put("loginUser", loginUser);
        modelMap.put("key", tenantKey);
        return "partner/user/user_list";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/user/list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getUsers(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<User> users = partnerTenantService.getUsers(tenantKey, tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(users).build();
    }

    @RequestMapping(value = "/partner/{tenant}/user/addUser", method = RequestMethod.GET)
    public String getCreateUserPage(@PathVariable("tenant") String tenantKey, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        if (tenantId == null)
            return "error";
        List<Map<String, Object>> groupNames = partnerTenantService.getUserGroupName(tenantId);
        User loginUser = (User) authService.currentUser();
        modelMap.put("loginUser", loginUser);
        modelMap.put("groupNames", groupNames);
        return "partner/user/createUser";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/user/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createUser(@PathVariable("tenant") String tenantKey, @RequestBody Map<String, String> body) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        try {
            User user = new User();
            String password = PasswordUtil.get(8);
            String userId =UUIDGenerator.getUUID();
            partnerTenantService.buildUserForCreate(body, user);
            user.setUserId(userId);
            user.setPassword(passwordEncoder.encode(password));
            user.setEnabled(1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            partnerTenantService.saveUser(tenantKey, tenantId, user);
            User currentUser = (User) authService.currentUser();
            User createUser = partnerTenantService.getUser(tenantKey,tenantId,userId);
            String content = currentUser.getUserName()+"于"+ simpleDateFormat.format(new Date())+"创建了用户"+"\""+createUser.getUserName()+"\"";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY,content,tenantKey+"_operate");

            return RestResponse.create(GlobalResponseCode.SUCCESS).putData(password).build();
//            return systemConfigService.sendMail(body.get("mail"),"账户初始密码推送","您的初始密码为："+password);
        } catch (SiemensException e) {
            return RestResponse.create(e).build();
        }
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/user/update", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateUser(@PathVariable("tenant") String tenantKey, @RequestBody Map<String, String> body) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        try {
            String userId = partnerTenantService.updateUser(tenantKey, tenantId, body);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User currentUser = (User) authService.currentUser();
            User updateUser = partnerTenantService.getUser(tenantKey,tenantId,userId);
            String content = currentUser.getUserName()+"于"+ simpleDateFormat.format(new Date())+"更新了用户"+"\""+updateUser.getUserName()+"\"的信息";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY,content,tenantKey+"_operate");

            return RestResponse.create(GlobalResponseCode.SUCCESS).putData(userId).build();
        } catch (SiemensException e) {
            return RestResponse.create(e).build();
        }
    }

    @RequestMapping(value = "/partner/{tenant}/api/vi/user/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateUserPwd(@PathVariable("tenant") String tenantKey, @RequestParam(value = "userId", required = true) String userId) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        try {
            String password = PasswordUtil.get(8);
            int i = partnerTenantService.updateUserPwd(tenantKey, tenantId, userId, passwordEncoder.encode(password));
            if(i == 1){
                User user = partnerTenantService.getUser(tenantKey,tenantId,userId);
                if(user != null){
//                    String email = user.getEmail();
//                    return systemConfigService.sendMail(email,"重置密码","新密码为："+password);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    User currentUser = (User) authService.currentUser();
                    User updateUser = partnerTenantService.getUser(tenantKey,tenantId,userId);
                    String content = currentUser.getUserName()+"于"+ simpleDateFormat.format(new Date())+"重置了用户"+"\""+updateUser.getUserName()+"\"的密码。";
                    writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY,content,tenantKey+"_operate");

                    return RestResponse.create(GlobalResponseCode.SUCCESS).putData(password).build();
                }
            }
        } catch (SiemensException e) {
            return RestResponse.create(e).build();
        }
        return RestResponse.create(GlobalResponseCode.ERROR_RESET_PASSWORD_FAIL).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/user/disabled", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteUser(@PathVariable("tenant") String tenantKey, @RequestParam(value = "userId", required = true) String userId) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        try {
            partnerTenantService.deleteUser(tenantKey, tenantId, userId);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User currentUser = (User) authService.currentUser();
            User updateUser = partnerTenantService.getUser(tenantKey,tenantId,userId);
            String content = currentUser.getUserName()+"于"+ simpleDateFormat.format(new Date())+"禁用了用户"+"\""+updateUser.getUserName()+"\"。";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY,content,tenantKey+"_operate");
            return RestResponse.create(GlobalResponseCode.SUCCESS)
                    .putData(userId)
                    .build();
        } catch (SiemensException e) {
            return RestResponse.create(e).build();
        }
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/user/recovery", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> recoveryUser(@PathVariable("tenant") String tenantKey, @RequestParam(value = "userId", required = true) String userId) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        try {
            partnerTenantService.recoveryUser(tenantKey, tenantId, userId);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User currentUser = (User) authService.currentUser();
            User updateUser = partnerTenantService.getUser(tenantKey,tenantId,userId);
            String content = currentUser.getUserName()+"于"+ simpleDateFormat.format(new Date())+"启用了用户"+"\""+updateUser.getUserName()+"\"。";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY,content,tenantKey+"_operate");
            return RestResponse.create(GlobalResponseCode.SUCCESS)
                    .putData(userId)
                    .build();
        } catch (SiemensException e) {
            return RestResponse.create(e).build();
        }
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/user/setMyPassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setMyPassword(@PathVariable("tenant") String tenantKey, @RequestBody Map<String, String> data) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        User loginUser = (User) authService.currentUser();
        if (!passwordEncoder.matches(data.get("oldPassword"), loginUser.getPassword())) {
            return RestResponse.create(GlobalResponseCode.ERROR_INCORRECT_PASSWORD).build();//mi  ma  cuo wu
        } else {
            loginUser.setPassword(passwordEncoder.encode(data.get("newPassword")));
        }
        try {
            partnerTenantService.updateUserPwd(tenantKey, tenantId, loginUser.getUserId(), loginUser.getPassword());

            return RestResponse.create(GlobalResponseCode.SUCCESS).build();
        } catch (SiemensException e) {
            e.printStackTrace();
            return RestResponse.create(e).build();
        }
    }

    @RequestMapping(value = "/partner/{tenant}/user/dashboard", method = RequestMethod.GET)
    public String getDashboardPage(@PathVariable("tenant") String tenantKey,
                                   String deviceId,
                                   ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        if (tenantId == null)
            return "error";
        User loginUser = (User) authService.currentUser();
//        Device device = partnerDeviceService.getDevice(tenantId, deviceId);
        Map<String,Object> device = partnerDeviceService.getDeviceAndState(tenantId, deviceId).get(0);
        modelMap.put("loginUser", loginUser);
        modelMap.put("key", tenantKey);
        modelMap.put("device", device);
        return "partner/dashboard";
    }

    @RequestMapping(value = "/partner/{tenant}/service/list", method = RequestMethod.GET)
    public String getuserService(@PathVariable("tenant") String tenantKey) {

        return "partner/user/service_state_list";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/user/services", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getTenantId(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String, Object>> list = partnerTenantService.getTenantServiceByTenantId(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    //dataTable search users
    @RequestMapping(value = "/partner/{tenant}/api/v1/user/listByDataTable", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getUsersByDataTable(@PathVariable("tenant") String tenantKey,
                                                   HttpServletRequest request) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        DataTableQuery dt = new DataTableQuery(request);

        if (dt.isDataTableRequest()){
            Map<String,Object> users = partnerTenantService.getUsersByDataTable(tenantKey,tenantId,request);
            return users;
        }

        return dt.buildResponse(0,0,new ArrayList<>());
    }

    //dataTable search service
    @RequestMapping(value = "/partner/{tenant}/api/v1/user/servicesByDataTable", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getTenantIdByDataTable(@PathVariable("tenant") String tenantKey,
                                                      HttpServletRequest request) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        DataTableQuery dt = new DataTableQuery(request);
        if (dt.isDataTableRequest()){
            Map<String, Object> service = partnerTenantService.getTenantServiceByIdAndDataTable(tenantId,request);
            return service;
        }
        return dt.buildResponse(0,0,new ArrayList<>());
    }
}
